/**
 * @fileOverview  Contains various UI functions in the namespace "oa.view" 
 * @author Gerd Wagner
 */
oa.view = {
  rf: {},  // subnamespace for rendering forms
  IE9: (navigator.userAgent.indexOf("Trident/5")>-1),
  operatorSymbols: ["+","−","&sdot;",":"],
  continueSymbol: "&#x25B6;",  // "►"
  // background colors (e.g. for memory cards) 
  backgroundColors: ['pink','plum','aqua','greenyellow','lightskyblue','palegreen','yellow','lime',"magenta","orange"],
  /**
   *  UI initialization is called when the HTML page is loaded
   */
  initializeUI: function () {
    document.getElementById("help").innerHTML = oa.trans("Help");
    document.getElementById("quit").innerHTML = oa.trans("Quit");
    if (oa.learner) { oa.view.showLearnerData(); }
    oa.view.renderLearningUnitSelectionList();
    oa.view.addEventHandlers();
    oa.view.initDialogWindow();
    oa.view.turnOnFullScreenMode();
  },
  /**
   *  Render the learning unit selection list
   */
  renderLearningUnitSelectionList: function () {
    var gradesEl = document.getElementById("grades"),
        gradeListItems = [],
        selectedGradeListItems = document.querySelectorAll("#grades>ul>li.selected"),
        subjectAreaSelList = document.querySelector("#subjectAreas>ul"),
        learningUnitSelList = document.querySelector("#learningUnits>ul"),
        headers = document.querySelectorAll("#learningUnitSelection h1"),
        txt = "";
    subjectAreaSelList.innerHTML = "";
    learningUnitSelList.innerHTML = "";
    for (var i=0; i < headers.length; i++) {
      headers[i].innerHTML = oa.trans( headers[i].innerHTML);
    }
    oa.view.renderGradeLevelList();
    if (oa.learner.grade > 0) {
      if (oa.showAllContents) { 
        gradesEl.classList.remove("hide");
        if (selectedGradeListItems.length > 0) {
          selectedGradeListItems[0].classList.remove("selected");
        }
        gradeListItems = gradesEl.querySelectorAll("ul>li");
        for (var i=0; i < gradeListItems.length; i++) {
          if (gradeListItems[i].innerHTML == oa.learner.grade) {
            gradeListItems[i].classList.add("selected");
          }        
        }
        txt = oa.trans("Show only subject areas for your grade level"); 
      } else {  // show only the learner's grade level
        gradesEl.classList.add("hide");
        txt = oa.trans("Show all grade levels"); 
      }
      subjectAreas = LearningUnit.getSubjectAreasByGrade( oa.learner.grade);
      learningUnits = LearningUnit.getLearningUnitsByGrade( oa.learner.grade);
      document.querySelector("#learningUnitSelection>p").innerHTML = txt;
    } else {  // no grade level entered
      subjectAreas = LearningUnit.getAllSubjectAreas(); 
      learningUnits = oa.learningUnits;
      gradesEl.classList.remove("hide");
      if (selectedGradeListItems.length > 0) {
        selectedGradeListItems[0].classList.remove("selected");
      }
      document.querySelector("#learningUnitSelection>p").innerHTML = "";
    }
    oa.view.displaySubjectAreas( subjectAreas);
    oa.view.displayLearningUnits( learningUnits);
  },
  /**
   * Render grade level list
   * 
   * @author Gerd Wagner
   * 
   * @param {array} gradeLevels  A list of grade levels
   */
  renderGradeLevelList: function () {
    var gradeLevelList = document.querySelector("#grades>ul"),
        gradeLevels = LearningUnit.getAllGradeLevels(),
        el=null;
    gradeLevelList.innerHTML = "";
    for (var i=0; i < gradeLevels.length; i++) {
      el = document.createElement("li");
      el.innerHTML = gradeLevels[i];
      gradeLevelList.appendChild( el);      
    }
  },
  /**
   * Display subject areas
   * 
   * @author Gerd Wagner
   * 
   * @param {array} subjectAreas  A list of subject areas
   */
  displaySubjectAreas: function (subjectAreas) {
    var subjectAreaSelList = document.querySelector("#subjectAreas>ul"),
        el=null;
    subjectAreaSelList.innerHTML = "";
    for (var i=0; i < subjectAreas.length; i++) {
      el = document.createElement("li");
      el.setAttribute('data-sa', subjectAreas[i]);
      el.innerHTML = oa.trans( subjectAreas[i]);
      subjectAreaSelList.appendChild( el);      
    }
  },
  /**
   * Display learning units
   * 
   * @author Gerd Wagner
   * 
   * @param {array} learningUnits  A list of learning units
   */
  displayLearningUnits: function (learningUnits) {
    var learningUnitSelList = document.querySelector("#learningUnits>ul"),
        el=null;
    learningUnitSelList.innerHTML = "";
    for (var i=0; i < learningUnits.length; i++) {
      el = document.createElement("li");
      el.appendChild( document.createTextNode( oa.trans( learningUnits[i].title)));
      learningUnitSelList.appendChild( el);
      el.setAttribute('title', oa.trans( learningUnits[i].description));
      el.setAttribute('data-luid', learningUnits[i].id);
    }
  },
  /**
   * Event handler for displaying subject areas when a grade is selected
   * 
   * @author Gerd Wagner
   */
  handleGradeSelectionEvents: function (e) {
    var grade = parseInt( e.target.innerHTML),
        subjectAreas = [], learningUnits = [],
        prevSelectedGradeElems = document.querySelectorAll("#grades>ul>li.selected");
    if (!grade) return;  // clicked in list, but no grade level selected
    if (prevSelectedGradeElems.length > 0) {
      prevSelectedGradeElems[0].classList.remove("selected");
      // distinguish between new selection and unselection
      if (prevSelectedGradeElems[0] !== e.target) {
        e.target.classList.add("selected");
        subjectAreas = LearningUnit.getSubjectAreasByGrade( grade);
        learningUnits = LearningUnit.getLearningUnitsByGrade( grade);
      } else {  // unselection
        subjectAreas = LearningUnit.getAllSubjectAreas();
        learningUnits = oa.learningUnits;
      }
    } else {  // no previous selection
      e.target.classList.add("selected");      
      subjectAreas = LearningUnit.getSubjectAreasByGrade( grade);
      learningUnits = LearningUnit.getLearningUnitsByGrade( grade);
    }
    oa.view.displaySubjectAreas( subjectAreas);
    oa.view.displayLearningUnits( learningUnits);
  },
  /**
   * Event handler for subject area selection events
   * Displays learning units
   * 
   * @author Gerd Wagner
   */
  handleSubjectAreaSelectionEvents: function (e) {
    var subjectArea = e.target.getAttribute("data-sa"),
        grade = 0;
        selectedGradeListItems = document.querySelectorAll("#grades>ul>li.selected"),
        prevSelectedSubjectAreaElems = document.querySelectorAll("#subjectAreas>ul>li.selected"),
        learningUnits = [],
        learningUnitSelList = document.querySelector("#learningUnits>ul"),
        el = null;
    if (!subjectArea) return;  // clicked in list, but no subjectArea selected
    learningUnitSelList.innerHTML = "";
    if (!oa.learner.grade || oa.showAllContents) {
      if (selectedGradeListItems.length > 0) {
        grade = parseInt( selectedGradeListItems[0].innerHTML);
      }
    } else if (oa.learner.grade > 0) {
      grade = oa.learner.grade;
    }
    if (prevSelectedSubjectAreaElems.length > 0) {
      prevSelectedSubjectAreaElems[0].classList.remove("selected");
      // distinguish between new selection and unselection
      if (prevSelectedSubjectAreaElems[0] !== e.target) {
        e.target.classList.add("selected");
        if (grade>0) {
          learningUnits = LearningUnit.getLearningUnitsByGradeAndSubjectArea( grade, subjectArea);
        } else {
          learningUnits = LearningUnit.getLearningUnitsBySubjectArea( subjectArea);          
        }
      } else {  // unselection
        if (grade>0) {
          learningUnits = LearningUnit.getLearningUnitsByGrade( grade);
        } else {
          learningUnits = oa.learningUnits;          
        }
      }
    } else {  // no previous selection
      e.target.classList.add("selected");
      if (grade>0) {
        learningUnits = LearningUnit.getLearningUnitsByGradeAndSubjectArea( grade, subjectArea);
      } else {
        learningUnits = LearningUnit.getLearningUnitsBySubjectArea( subjectArea);          
      }
    }
    oa.view.displayLearningUnits( learningUnits);
  },
  /**
   * Event handler for starting a learning unit when selected from the
   * learning unit selection list 
   * 
   * @author Gerd Wagner
   */
  startLearningUnit: function (e) {
    var lu = e.target.getAttribute("data-luid");
    if (!lu) return;  // clicked in list, but no learningUnit selected
    document.getElementById("learningUnitSelection").classList.toggle("hide");
    document.getElementById("renderBox").classList.toggle("show");
    document.getElementById("sessionInfo").classList.toggle("show");
    oa.ctrl.startLearningUnit( lu);
  },
  /**
   *  Reset the screen: 
   *  1) Delete session data
   *  2) Restore learning unit selection list
   *  3) Delete renderBox contents
   *  4) Hide Tito
   */
  resetScreen: function () {
    var rB = document.getElementById("renderBox");
    if (document.body.getAttribute("class") === "stars") { oa.view.rf.animatedStars.resetStyle(); }
    document.getElementById("sessionInfo").classList.toggle("show");
    document.getElementById("learningUnitSelection").classList.toggle("hide");
    oa.view.hideHelpButton();
    oa.view.hideQuitButton();
    rB.innerHTML = "";
    rB.classList.toggle("show");
    // oa.view.toggleTito();
  },
  /**
   *  Show learner data
   */
  showLearnerData: function () {
    document.getElementById("learnerData").innerHTML = oa.trans("For") +
      " "+ oa.learner.firstName +", "+ oa.trans("grade level") +" "+ oa.learner.grade;
    document.getElementById("editLearnerData").innerHTML = oa.trans("Edit");
  },
  /**
  *  Add the event listeners for the general user interface
  */
  addEventHandlers: function () {
    document.querySelector("#learningUnits>ul").addEventListener("click", 
        oa.view.startLearningUnit);
    document.querySelector("#subjectAreas>ul").addEventListener("click", 
        oa.view.handleSubjectAreaSelectionEvents);
    document.querySelector("#grades>ul").addEventListener("click", 
        oa.view.handleGradeSelectionEvents);
    document.getElementById("help").addEventListener("click", oa.view.help);
    document.getElementById("quit").addEventListener("click", oa.ctrl.quit);
    document.getElementById("editLearnerData").addEventListener('click', oa.view.openDialogWindow);
    document.getElementById("closeDialog").addEventListener('click', oa.view.closeDialogWindow);
    document.getElementById("reset").addEventListener('click', oa.view.resetData);
    document.getElementById("showAll").addEventListener('click', function () { 
      oa.showAllContents = !oa.showAllContents;
      oa.view.renderLearningUnitSelectionList();
    });
    /*
    // close dialog window also when its surrounding is clicked
    document.querySelector('.overlay').addEventListener('click', function (e) {
      if (/overlay|wrap/.test(e.target.className)) { oa.view.closeDialogWindow(); }
    });
    */
  },
  /**
   *  Init dialog window
   */
  initDialogWindow: function () {
    var fInp = document.getElementById("firstNameInput"),
        fLbl = document.createTextNode( oa.trans("First name") + ":"),
        gInp = document.getElementById("gradeInput"),
        gLbl = document.createTextNode( oa.trans("Grade level") + ":"),
        lSel = document.getElementById("languageSelect"),
        lLbl = document.createTextNode( oa.trans("Language") + ":");
    fInp.title = oa.trans("Please enter a name!");
    // assign label by accessing the input's parent element
    fInp.parentNode.insertBefore( fLbl, fInp);
    gInp.title = oa.trans("Please enter a number between 1 and 12!");
    gInp.parentNode.insertBefore( gLbl, gInp);
    oa.view.constructLanguageOptions( lSel);
    lSel.parentNode.insertBefore( lLbl, lSel);
    document.getElementById("dialog-title").innerHTML = oa.trans("Your Data");
    document.getElementById("closeDialog").value = oa.trans("OK");
    document.getElementById("reset").innerHTML = oa.trans("Reset");
  },    
  /**
   *  Construct language selection options
   */
  constructLanguageOptions: function ( langSel) {
    var opt = {};
    for (var i=0; i < oa.supportedLanguages.length; i++) {
      opt = document.createElement("option");
      opt.value = oa.supportedLanguages[i];
      opt.innerHTML = util.languageNames[opt.value];
      if (opt.value === oa.learner.language) {
        opt.setAttribute("selected", "selected");
      }
      langSel.appendChild( opt);    
    }
  },
  /**
   *  Open dialog window
   */
  openDialogWindow: function () {
    var fInp = document.getElementById("firstNameInput"),
        gInp = document.getElementById("gradeInput"),
        elem = {};
    if (oa.learner.firstName) {
      fInp.value = oa.learner.firstName;
      gInp.value = oa.learner.grade;
      if (oa.basicAdditionStatistics.length > 0) {
        elem = document.getElementById("additionTbl");
        oa.view.fillBasicProblemStatistics( oa.basicAdditionStatistics, elem);
      }
      if (oa.basicMultiplicationStatistics.length > 0) {
        elem = document.getElementById("multiplicationTbl");
        oa.view.fillBasicProblemStatistics( oa.basicMultiplicationStatistics, elem);
      }
    }
    document.body.classList.toggle("overlaid");
  },    
  /**
   *  Close dialog window
   */
  closeDialogWindow: function (e) {
    var fInp = document.getElementById("firstNameInput"),
        lSel = document.getElementById("languageSelect"),
        gInp = document.getElementById("gradeInput"),
        g = 0;
    if (fInp.value) {  // write form field data to corresponding learner attributes
      oa.learner.setFirstName( fInp.value);
      g = parseInt( gInp.value);
      if (!isNaN(g) && g !== oa.learner.grade) {
        oa.learner.setGrade(g);
        oa.viw.renderLearningUnitSelectionList();
      }
      if (lSel.value !== oa.learner.language) {
        oa.learner.setLanguage( lSel.value);
      }
      // update the screen
      oa.view.showLearnerData();
      // close dialog window
      document.body.classList.toggle("overlaid");
    } else {
      oa.ctrl.resetData();
    }
    e.preventDefault();
  },
  /**
   * Turn the full screen mode on
   * DOESN'T WORK???
   */
  turnOnFullScreenMode: function () {
    var elem = document.querySelector("#renderBox");  
    if (elem.requestFullScreen) { elem.requestFullScreen();} 
    else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen();} 
    else if (elem.webkitRequestFullScreen) { elem.webkitRequestFullScreen();}    
  },
  /**
   *  Clear learner data
   */
  clearLearnerData: function () {
    document.getElementById("learnerData").innerHTML = "";
    document.getElementById("firstNameInput").value = "";
    document.getElementById("gradeInput").value = "";
    oa.learner = new Learner();
    oa.basicAdditionStatistics = [];
    oa.basicMultiplicationStatistics = [];
  },    
  /**
   * Fill in the learning unit header data
   * 
   * @param {LearningUnit} lu  A learning unit.
   */
  fillLearningUnitHeader : function ( lu) {
    document.querySelector("#sessionInfo>h1").innerHTML = oa.trans( lu.title);
    document.getElementById("nmrOfProblems").innerHTML = "("+ oa.trans("of") +" "+ lu.getNmrOfProblems()+")";
  },
  /**
   * Fill in the session info labels
   */
  fillLabels: function () {
    document.getElementById("labelProblemCounter").innerHTML = oa.trans("Problem");
    document.getElementById("labelPercentageCorrect").innerHTML = oa.trans("Correct:");     
   },
   /**
    * Fill in the exercise header data
    * 
    * @param {ArithmeticExercise} ae  An arithmetic exercise.
    */
   fillExerciseHeader : function (ae) {
     document.querySelector("#sessionInfo>h2").innerHTML = oa.trans( ae.problemType.title);
   },
   /**
    * Hide evaluation info
    */
   hideEvaluationInfo: function () {
     document.getElementById("evaluationInfo").style.visibility = "hidden";
    },
   /**
    * Show evaluation info
    */
    showEvaluationInfo: function () {
      document.getElementById("evaluationInfo").style.visibility = "visible";
     },
   /** 
    *  Fill in basic addition statistics data
    */
   fillBasicProblemStatistics: function ( basicProblemStatistics, tblElem) {
     var rows = tblElem.querySelectorAll("tbody>tr"),
         cells = [],
         count = 0;
     for (var i=0; i < 10; i++) {
       cells = rows[i].querySelectorAll("td");
       for (var j=0; j < 10; j++) {
         count = basicProblemStatistics[i*10 + j].correctCounter;
         cells[j].innerHTML = count;
         // data-count is used for coloring the cells with 5 different greens
         cells[j].setAttribute('data-count', Math.min( count, 5));
       }
     }
   },
   /**
    * FOR LENZ ONLY!!!
    * Show/hide Tito
    */
   toggleTito : function () {
     document.querySelector("#tito").classList.toggle("show");
   },
   /**
    * reset persistent data by clearing local storage
    */
   resetData: function () {
     if (confirm( oa.trans("Do you really want to clear all data?"))) {
       oa.ctrl.resetData();
     }
   },
   /**
    * show smiling Ari
    */
   showSmilingAri: function () {
     document.querySelector("#ari-smiling").classList.remove("hide");
     document.querySelector("#ari-disappointed").classList.remove("show");
     document.querySelector("#ari-worried").classList.remove("show");
   },
   /**
    * show worried Ari
    */
   showWorriedAri: function () {
     document.querySelector("#ari-smiling").classList.add("hide");
     document.querySelector("#ari-disappointed").classList.remove("show");
     document.querySelector("#ari-worried").classList.add("show");
   },
   /**
    * show disappointed Ari
    */
   showDisappointedAri: function () {
     document.querySelector("#ari-smiling").classList.add("hide");
     document.querySelector("#ari-worried").classList.remove("show");
     document.querySelector("#ari-disappointed").classList.add("show");
   },
   /**
    * show percentage of correct answers
    */
   showPercentageCorrect: function (percentageCorrect) {
     document.getElementById("percentageCorrect").innerHTML = percentageCorrect + " %";
   },
   /**
    * show help during exercises 
    */
   help: function () {
     var ehtElem = document.getElementById("exerciseHelpText"); 
     ehtElem.innerHTML = oa.trans( oa.currentExercise.renderingForm.helpText);
     ehtElem.style.display = "block";
     window.setTimeout( oa.view.endExerciseHelp, 3000);
   },
   /**
    * end exercise help 
    */
   endExerciseHelp: function () {
     var ehtElem = document.getElementById("exerciseHelpText"); 
     ehtElem.innerHTML = "";
     ehtElem.style.display = "none";
   },
   /**
    * hide help button 
    */
   hideHelpButton: function () {
     document.getElementById("help").style.visibility = "hidden";       
   },
   /**
    * show help button 
    */
   showHelpButton: function () {
     document.getElementById("help").style.visibility = "visible";       
   },
   /**
    * hide (help+)quit button 
    */
   hideQuitButton: function () {
     // document.getElementById("help-quit").style.visibility = "hidden";       
     document.getElementById("help-quit").style.display = "none";       
   },
   /**
    * show (help+)quit button 
    */
   showQuitButton: function () {
     // document.getElementById("help-quit").style.visibility = "visible";       
     document.getElementById("help-quit").style.display = "block";       
   }
 };
